#include <windows.h>
#include <strsafe.h>
#include "..\common\string.h"

//#include "memorymanager.h"
#include "engine.h"


#define DIR_CHILDREN_COUNT 7
string g_dirChildren[DIR_CHILDREN_COUNT] = 
{string(),string("content\\"),string("content\\models\\"),string("content\\textures\\"),string("content\\maps\\"),string("content\\sounds\\"),string("content\\shaders\\")}; 

const string CEngine::FindFilepath(const string &sz_filename)
{
	if(sz_filename.IsValid()) 
	{
		TCHAR szSearchResult [ MAX_PATH ] = {0}; 
		WIN32_FIND_DATA findData; 
		HANDLE findHandle = NULL; 
		for(int i = 0;  i < DIR_CHILDREN_COUNT;  i++)
		{
			string szSearchFilePath;
			szSearchFilePath = string("Default\\");
			szSearchFilePath.concat(g_dirChildren[i]); 
			szSearchFilePath.concat(sz_filename); 
			findHandle = FindFirstFile(szSearchFilePath.c_str(),&findData); 
			if(findHandle != INVALID_HANDLE_VALUE)
			{
				FindClose(findHandle); 
				return szSearchFilePath; 
			}
		}

		if(m_ContentDir.IsValid())
		{
			string contentDirPath = m_ContentDir;
			contentDirPath.concat('\\');

			for(int i = 0;  i < DIR_CHILDREN_COUNT;  i++)
			{
				string szSearchFilePath;
				szSearchFilePath = contentDirPath;
				szSearchFilePath.concat(g_dirChildren[i]); 
				szSearchFilePath.concat(sz_filename); 

				findHandle = FindFirstFile(szSearchFilePath.c_str(),&findData); 
				if(findHandle != INVALID_HANDLE_VALUE)
				{
					FindClose(findHandle); 
					return szSearchFilePath; 
				}
			}
		}

		if(findHandle != NULL)
			FindClose(findHandle); 
	}

	return ""; 
}

FILE *CEngine::FindFile(const string &sz_filename)
{
	const string filepath = FindFilepath(sz_filename); 

	if(filepath.length() == 0) 
		return NULL; 

	return fopen(filepath.c_str(), "rb"); 
}